package com.hos.handlers;

import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.hos.vo.CheckingResultImgVo;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.util.List;

/**
 * @author ：njh
 * @date ：Created in 2023/12/20 14:27
 * @description：
 * @modified By：
 * @version:
 */
@MappedTypes({CheckingResultImgVo.class})
@MappedJdbcTypes(value = JdbcType.VARCHAR)
public class JsonTypeHandler extends AbstractJsonTypeHandler<Object> {

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected Object parse(String json) {
        if (Strings.isNullOrEmpty(json)) {
            return new CheckingResultImgVo();
        }
        try {
            return objectMapper.readValue(json, new TypeReference<List<CheckingResultImgVo>>(){});
        } catch (JsonProcessingException e) {
            throw new RuntimeException("类型转换失败", e);
        }
    }

    @Override
    protected String toJson(Object obj) {
        if (obj == null) {
            return "[]";
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("类型转换失败", e);
        }
    }
}